Android SDK 對於行動網路的開關一直屬於非公開的部分,
不過目前(版本4.4以前)還是可以透過Java relection的方式來實現
方法如下:
public static boolean isMobileDataEnabled(ConnectivityManager cm){
try {
Method method = cm.getClass().getMethod("getMobileDataEnabled");
return (Boolean) method.invoke(cm);
} catch (NoSuchMethodException e) {
Log.d(TAG,"NoSuchMethodException");
} catch (Exception e) {
Log.d(TAG,"Exception");
}
return false;
}
private void setMobileDataEnabled(boolean onOff) {
boolean isOn = isMobileDataEnabled(connectivityManager);
if((onOff && isOn) || (!onOff && !isOn)){
return;
}
try {
Method method = connectivityManager.getClass().getMethod("setMobileDataEnabled", boolean.class);
method.invoke(connectivityManager, onOff);
} catch (NoSuchMethodException e) {
Log.d(TAG,"NoSuchMethodException");
} catch (Exception e) {
Log.d(TAG,"Invoke Exception");
}
}
但因為是非公開API, 也許哪一天這個方法也會被擋掉也說不定